package org.victoria.csms.interceptor;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.victoria.common.utils.FrontUtils;
import org.victoria.csms.domain.User;
import org.victoria.csms.service.UserService;
import sun.misc.BASE64Decoder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by handoop on 2015/4/7.
 */
public class AutoLoginInterceptor implements HandlerInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(AutoLoginInterceptor.class);
    @Autowired private UserService _user;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        logger.error("the URI is " + FrontUtils.getURI(request) + " , auto login interceptor");
        Subject subject = SecurityUtils.getSubject();
        if (!subject.isAuthenticated()) {
            logger.error("had not authenticated, now we is authenticating...");
            Cookie[] cookies = request.getCookies();
            if (cookies!=null){
                logger.error("checking cookie...");
                for (Cookie cookie : cookies){
                    if (cookie.getName().equals(FrontUtils.AUTO_LOGIN_FIELD)){
                        logger.error("handler the cookie, cookie value is " + cookie.getValue());
                        String username = cookie.getValue().split("_")[0];
                        String password = cookie.getValue().split("_")[1];
                        username = new String(new BASE64Decoder().decodeBuffer(username));
                        password = new String(new BASE64Decoder().decodeBuffer(password));
                        User user = _user.getUserByAccount(username);
                        if (user!=null){
                            if (password.toLowerCase().equals(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()).toLowerCase())){
                                UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());
                                logger.error("authentication is successful, loginning...");
                                subject.login(token);//登录
                                request.getSession().setAttribute(FrontUtils.USER_KEY, user);
                            }
                        }
                    }
                }
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
